package com.graduation.apiservice.task;

import com.graduation.common.constans.EsConstants;
import com.graduation.pojo.po.LegalDocument;
import com.graduation.service.LegalDocumentService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 初始化es索引和数据，如果需要重新同步只需要打开Component注解即可
 */
@Slf4j
//@Component
public class LegalDocumentDataToEsTask {

    @Resource
    private ElasticsearchOperations elasticsearchOperations;

    @Resource
    private LegalDocumentService legalDocumentService;

    /**
     * 应用启动完成后执行初始化
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        log.info("应用启动完成，开始初始化ES数据...");
        initMapping();
        buildEsData();
        log.info("ES数据初始化完成！");
    }

    /**
     * 创建ES索引和映射
     */
    public void initMapping() {
        try {
            IndexCoordinates indexCoordinates = IndexCoordinates.of(EsConstants.LEGAL_DOCUMENT_INDEX);
            
            // 检查索引是否存在
            if (elasticsearchOperations.indexOps(indexCoordinates).exists()) {
                log.info("ES索引 {} 已存在，跳过创建", EsConstants.LEGAL_DOCUMENT_INDEX);
                return;
            }
            
            // 创建索引
            boolean created = elasticsearchOperations.indexOps(indexCoordinates).create();
            if (created) {
                log.info("ES索引 {} 创建成功", EsConstants.LEGAL_DOCUMENT_INDEX);
                
                // 设置映射
                boolean mappingCreated = elasticsearchOperations.indexOps(indexCoordinates)
                    .putMapping(elasticsearchOperations.indexOps(indexCoordinates)
                        .createMapping(LegalDocument.class));
                
                if (mappingCreated) {
                    log.info("ES索引 {} 映射创建成功", EsConstants.LEGAL_DOCUMENT_INDEX);
                } else {
                    log.error("ES索引 {} 映射创建失败", EsConstants.LEGAL_DOCUMENT_INDEX);
                }
            } else {
                log.error("ES索引 {} 创建失败", EsConstants.LEGAL_DOCUMENT_INDEX);
            }
        } catch (Exception e) {
            log.error("创建ES索引和映射失败", e);
        }
    }

    /**
     * 同步所有法律文档数据到ES
     */
    public void buildEsData() {
        try {
            log.info("开始同步法律文档数据到ES...");
            
            // 查询所有法律文档
            List<LegalDocument> allDocuments = legalDocumentService.list();
            if (allDocuments.isEmpty()) {
                log.info("没有找到法律文档数据，跳过同步");
                return;
            }
            
            log.info("共找到 {} 条法律文档数据，开始批量同步到ES", allDocuments.size());
            
            // 批量保存到ES
            Iterable<LegalDocument> savedDocuments = elasticsearchOperations.save(allDocuments);
            
            int count = 0;
            for (LegalDocument doc : savedDocuments) {
                count++;
            }
            
            log.info("成功同步 {} 条法律文档数据到ES", count);
            
        } catch (Exception e) {
            log.error("同步法律文档数据到ES失败", e);
        }
    }

}
